<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="模板类型" prop="industryId">
              <el-select v-model="queryParams.industryId" placeholder="请选择模板类型" clearable>
                <el-option v-for="dict in templateTypeList" :key="dict.industryId" :label="dict.industryName" :value="dict.industryId" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Upload" @click="handleImport">导入</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="feedbackList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="" align="center" prop="feedbackId" v-if="true" /> -->
        <el-table-column label="模板名称" align="center" prop="templateName" />
        <el-table-column label="模板类型" align="center" prop="industryName">
          <template #default="scope">
            <el-tag v-show="scope.row.industryName">{{ scope.row.industryName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="模板描述" align="center" prop="templateDescription" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="template_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="图片" align="center" prop="templatePreviewImage">
          <template #default="scope">
            <el-image :src="scope.row.templatePreviewImage" :preview-teleported="true" :width="100" :height="100" />
          </template>
        </el-table-column>
        <el-table-column label="系统预设模板" align="center" prop="isSystem">
          <template #default="scope">
            <dict-tag :options="sys_is_no" :value="scope.row.isSystem" />
          </template>
        </el-table-column>
        <el-table-column label="预设模块" align="center" prop="modelNames">
          <template #default="scope">
            <dict-tag :options="sys_is_modelnames" :value="scope.row.modelNames" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 用户导入对话框 -->
    <el-dialog v-model="uploadOpen" :title="uploadTitle" width="700px" append-to-body>
      <el-form ref="uploadFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板类型" prop="industryId">
          <el-select v-model="form.industryId" placeholder="请选择模板类型" clearable>
            <el-option v-for="item in templateTypeList" :key="item.industryId" :label="item.industryName" :value="item.industryId" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板描述" prop="templateDescription">
          <el-input v-model="form.templateDescription" placeholder="请输入模板描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" clearable>
            <el-option v-for="dict in template_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="系统预设模板" prop="isSystem">
          <el-select v-model="form.isSystem" placeholder="请选择系统预设模板" clearable>
            <el-option v-for="dict in sys_is_no" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="预设模块" prop="modelNames">
          <div class="custom-select-with-drag">
            <el-select v-model="form.modelNames" placeholder="请选择预设模块" clearable multiple collapse-tags class="custom-select">
              <el-option v-for="dict in sys_is_modelnames" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
            <div v-if="form.modelNames && form.modelNames.length" class="tags-container">
              <transition-group name="sort-list" tag="div" class="tag-list">
                <div
                  v-for="(tag, index) in form.modelNames"
                  :key="tag"
                  class="draggable-tag"
                  draggable="true"
                  @dragstart="dragStart($event, index)"
                  @dragover.prevent
                  @dragenter.prevent
                  @drop="drop($event, index)"
                >
                  <el-tag closable @close="handleTagClose(tag)" class="tag-item">
                    {{ findLabelByValue(tag) }}
                  </el-tag>
                </div>
              </transition-group>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="上传图片" prop="isUpdate ? '' : 'templatePicPath'">
          <el-upload
            class="template-uploader"
            ref="uploadPicRef"
            :file-list="uploadPicList"
            :limit="1"
            :headers="uploadHeaders"
            :action="uploadUrl"
            :show-file-list="isUpdate"
            :on-success="handleFileSuccess(0)"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.templatePicPath" :src="form.templatePicPath" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="上传文件" :prop="isUpdate ? '' : 'templatePath'" v-show="!isUpdate"> -->
        <el-form-item label="上传文件" prop="templatePath">
          <el-upload
            ref="uploadRef"
            :file-list="uploadFileList"
            :limit="1"
            :headers="uploadHeaders"
            :action="uploadUrl"
            :disabled="uploadIsUploading"
            :on-progress="handleFileUploadProgress(1)"
            :on-success="handleFileSuccess(1)"
            :auto-upload="true"
            drag
          >
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled />
            </el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="text-center el-upload__tip">
                <!-- <span>仅允许导入xls、xlsx格式文件。</span> -->
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="cancelForm">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="Feedback" lang="ts">
import { ref, reactive, toRefs, onMounted, getCurrentInstance, nextTick } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import type { FormInstance as ElFormInstance } from 'element-plus';
import { listModule, delModule, addModule, getModule, updateModule } from '@/api/aiManage/module/index';
import { globalHeaders } from '@/utils/request';
import { Plus } from '@element-plus/icons-vue';
import {
  listResumeTemplateIndustryType,
  getResumeTemplateIndustryType,
  delResumeTemplateIndustryType,
  addResumeTemplateIndustryType,
  updateResumeTemplateIndustryType
} from '@/api/aiManage/templateType/index';
import { ElMessage } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { module_type, template_status, sys_is_no, sys_is_modelnames } = toRefs<any>(
  proxy?.useDict('module_type', 'template_status', 'sys_is_no', 'sys_is_modelnames')
);

const feedbackList = ref([]);
const baseList = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const uploadOpen = ref(false);
const uploadTitle = ref('');
const isUpdate = ref(false);
const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload';
const uploadIsUploading = ref(false);
const uploadHeaders = globalHeaders();
const uploadRef = ref(null);
const uploadPicRef = ref(null);
const uploadFormRef = ref<ElFormInstance>();

const queryFormRef = ref<ElFormInstance>();
const feedbackFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData = {
  templateId: undefined,
  templateName: undefined,
  industryId: undefined,
  industryName: undefined,
  templatePicPath: undefined,
  templatePath: undefined,
  templateDescription: undefined,
  status: undefined,
  isSystem: undefined,
  modelNames: undefined
};
const data = reactive<PageData<any, any>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    industryId: undefined,
    params: {}
  },
  rules: {
    templateName: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
    // templateType: [{ required: true, message: '模板类型不能为空', trigger: 'change' }],
    // templatePath: [{ required: true, message: '上传文件不能为空', trigger: 'blur' }],
    templatePicPath: [{ required: true, message: '上传图片不能为空', trigger: 'blur' }],
    // templateDescription: [{ required: true, message: '模板描述不能为空', trigger: 'blur' }],
    // status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
    modelNames: [{ required: true, message: '预设模块不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const templateTypeList = ref([]);

// 添加上传文件预览列表状态
const uploadPicList = ref<any[]>([]);
const uploadFileList = ref<any[]>([]);

/** 查询意见反馈列表 */
const getList = async () => {
  loading.value = true;
  const res = await listModule(queryParams.value);
  baseList.value = res.rows.forEach((element) => {
    element.modelNames = JSON.parse(element.modelNames);
  });
  feedbackList.value = res.rows;
  // feedbackList.value.modelNames = JSON.parse(feedbackList.value.modelNames);
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  feedbackFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map((item) => item.templateId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset();
  uploadOpen.value = true;
  uploadTitle.value = '修改数据';
  isUpdate.value = true;
  const res = await getModule(row.templateId);
  form.value = res.data;
  form.value.modelNames = JSON.parse(form.value.modelNames);

  // 设置已上传图片的预览
  if (form.value.templatePreviewImage) {
    uploadPicList.value = [
      {
        name: '已上传图片',
        url: form.value.templatePreviewImage
      }
    ];
  } else {
    uploadPicList.value = [];
  }

  // 设置已上传文件的预览
  if (form.value.fileUrl) {
    uploadFileList.value = [
      {
        name: '已上传文件',
        ossId: form.value.fileUrl
      }
    ];
  } else {
    uploadFileList.value = [];
  }

  console.log(form.value);
};

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  const _moduleIds = row?.templateId || ids.value;
  await proxy?.$modal.confirm('是否确认删除当前数据项？').finally(() => (loading.value = false));
  await delModule(_moduleIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/resumeTemplate/export',
    {
      ...queryParams.value
    },
    `module_${new Date().getTime()}.xlsx`
  );
};

/** 导入按钮操作 */
const handleImport = () => {
  uploadOpen.value = true;
  uploadTitle.value = '用户导入';
  isUpdate.value = false;
  form.value = { ...initFormData };
  // 清空上传预览列表
  uploadPicList.value = [];
  uploadFileList.value = [];
  // 重置上传组件
  nextTick(() => {
    if (uploadRef.value || uploadPicRef.value) {
      uploadRef.value.clearFiles();
      uploadPicRef.value.clearFiles();
    }
  });
};

const beforeAvatarUpload = (rawFile) => {
  const type = ['image/jpeg', 'image/jpg', 'image/png'];
  const isJPG = type.includes(rawFile.type);
  //检验文件格式
  if (!isJPG) {
    proxy?.$modal.msgError(`请上传图片！`);
    return false;
  }
  return true;
};

/** 文件上传中处理 */
const handleFileUploadProgress = (index: number) => (event: any, file: any) => {
  uploadIsUploading.value = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (index: number) => (response: any, file: any) => {
  if (response.code === 200) {
    uploadIsUploading.value = false;
    // 保存ossId到form.templatePath
    if (index === 0) {
      form.value.templatePicPath = response.data.url;
      // 更新图片预览列表
      uploadPicList.value = [
        {
          name: file.name || '已上传图片',
          url: response.data.url
        }
      ];
    } else {
      form.value.templatePath = response.data.ossId;
      // 更新文件预览列表
      uploadFileList.value = [
        {
          name: file.name || '已上传文件',
          ossId: response.data.ossId
        }
      ];
    }
    proxy?.$modal.msgSuccess('文件上传成功');
  } else {
    proxy?.$modal.msgError('文件上传失败');
    uploadIsUploading.value = false;
  }
};

/** 提交上传文件 */
const submitFileForm = () => {
  console.log(form.value);
  (uploadFormRef.value as any).validate((valid: boolean) => {
    if (valid) {
      if (isUpdate.value) {
        updateModule({
          templateId: form.value.templateId,
          ossId: form.value.templatePath,
          status: form.value.status,
          isSystem: form.value.isSystem,
          modelNames: JSON.stringify(form.value.modelNames),
          industryId: form.value.industryId,
          industryName: templateTypeList.value.find((item: any) => item.industryId === form.value.industryId)?.industryName,
          templateDescription: form.value.templateDescription,
          templatePreviewImage: form.value.templatePicPath,
          templateName: form.value.templateName
        }).then((res: any) => {
          if (res.code === 200) {
            proxy?.$modal.msgSuccess('修改成功');
            uploadOpen.value = false;
            form.value = { ...initFormData };
            getList();
          } else {
            proxy?.$modal.msgError('修改失败');
            form.value = { ...initFormData };
          }
        });
      } else {
        addModule({
          ossId: form.value.templatePath,
          status: form.value.status,
          isSystem: form.value.isSystem,
          modelNames: JSON.stringify(form.value.modelNames),
          industryId: form.value.industryId,
          industryName: templateTypeList.value.find((item: any) => item.industryId === form.value.industryId)?.industryName,
          templateDescription: form.value.templateDescription,
          templatePreviewImage: form.value.templatePicPath,
          templateName: form.value.templateName
        }).then((res: any) => {
          if (res.code === 200) {
            proxy?.$modal.msgSuccess('导入成功');
            uploadOpen.value = false;
            form.value = { ...initFormData };
            getList();
          } else {
            proxy?.$modal.msgError('导入失败');
            form.value = { ...initFormData };
          }
        });
      }
    }
  });
};

const cancelForm = () => {
  uploadOpen.value = false;
  form.value = { ...initFormData };
  // 重置上传组件
  if (uploadRef.value || uploadPicRef.value) {
    uploadRef.value.clearFiles();
    uploadPicRef.value.clearFiles();
  }
};

/* 获取模板类型 */
const getModuleType = async () => {
  const res = await listResumeTemplateIndustryType();
  templateTypeList.value = res.rows;
};

/* 获取模板类型 */
const getTemplateType = (templateType: string) => {
  console.log('templateType', templateType);
  return templateTypeList.value.find((item: any) => item.industryCode === templateType)?.industryName;
};

// 拖拽开始
const dragStart = (event: DragEvent, index: number) => {
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move';
    event.dataTransfer.setData('text/plain', index.toString());
  }
};

// 拖拽放置
const drop = (event: DragEvent, index: number) => {
  if (event.dataTransfer) {
    const fromIndex = Number(event.dataTransfer.getData('text/plain'));
    if (fromIndex !== index) {
      // 重新排序数组
      const newModelNames = [...form.value.modelNames];
      const item = newModelNames.splice(fromIndex, 1)[0];
      newModelNames.splice(index, 0, item);
      form.value.modelNames = newModelNames;
    }
  }
};

// 关闭标签时从选中值中移除
const handleTagClose = (value: any) => {
  const index = form.value.modelNames.indexOf(value);
  if (index !== -1) {
    form.value.modelNames.splice(index, 1);
  }
};

// 根据值查找对应的标签文本
const findLabelByValue = (value: any) => {
  const found = sys_is_modelnames.value.find((item) => item.value === value);
  return found ? found.label : value;
};

onMounted(() => {
  getList();
  getModuleType();
});
</script>
<style lang="scss">
.template-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.template-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.custom-select-with-drag {
  width: 100%;
}
.custom-select-with-drag .custom-select {
  width: 100%;
  margin-bottom: 8px;
}
.custom-select-with-drag .tags-container {
  margin-top: 8px;
}
.custom-select-with-drag .tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.custom-select-with-drag .draggable-tag {
  cursor: move;
  margin: 4px;
  transition: all 0.3s;
}
.custom-select-with-drag .tag-item {
  display: flex;
  align-items: center;
  white-space: nowrap;
}

/* 拖拽排序动画 */
.sort-list-move {
  transition: transform 0.5s;
}
.sort-list-enter-active,
.sort-list-leave-active {
  transition: all 0.5s;
}
.sort-list-enter-from,
.sort-list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}
</style>
